函式在被宣告定義的當下不會執行,而是在調用的時候被執行。
JavaScript 函式(function) 被調用的方式如下:
call()與apply() 方法間接調用。JavaScript 用來呼叫(或執行)函式或方法的語法。
// 函式調用的運算式一定會包含函式運算式 + 括號 + 引數運算式
f(0) // f 為函式運算式, 0 為引數運算式
Math.max(x,y,z) // Math.max() 為函式,x,y,z 是引數
a.sort(); // a.sort 沒有引數的函式
在 JavaScript 中呼叫一個函式時,會發生以下的事情:
call() 方法的物件),那麼 JavaScript 會拋出一個 TypeError 錯誤。return回傳一個值,那這個值就是整個函式調用表達式的值,return沒有值的話,傳回的是undefined。return 回傳一個值,那麼值將會是 undefined。若提供的引數太少,那麼缺少的參數值會被賦予
undefined。
若提供的引數太多,那多餘的引數將被忽略。
方法(method) 是存在於物件中的JavaScript 函式。
obj.method = funcName; // 將 funcName 函式指定給物件的 method
obj.method(); // 調用物件的方法
obj.method(x,y); // 調用有引數的物件方法
function funcName(){
//....
}
this 來參考此物件:
var calculator = {
operandOne: 1,
operandTwo: 2,
plus: function(){
// this
this.result = this.operandOne + this.operandTwo;
},
minus: function(){
this.result = this.operandOne - this.operandTwo;
},
times: function(){
this.result = this.operandOne * this.operandTwo;
},
divided: function(){
this.result = this.operandOne / this.operandTwo;
}
};
calculator.plus();
calculator.result // 3